﻿using GameSave.Common.Misc;
using GameSave.Infrastructure.Entities;
using GameSave.Infrastructure.Message;
using Quick;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace GameSave.UI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly MainWindowVM _DataVM;
        //当前窗口句柄
        private IntPtr m_Hwnd = new IntPtr();
        private Dictionary<EHotKeyAction, int> dicKeyRegParam;

        public MainWindow(MainWindowVM mainVM)
        {
            InitializeComponent();
            _DataVM = mainVM;
            this.DataContext = _DataVM;
            Messenger.Default.Register<BackupDescFocusMessage>(this, msg =>
            {
                SelectBackupDescText(msg);
            });
        }

        /// <summary>
        /// 点击 修改备份记录名称 按钮时，自动全选描述
        /// </summary>
        /// <param name="msg"></param>
        private void SelectBackupDescText(BackupDescFocusMessage msg)
        {
            if (msg.Selectedbackup != null)
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    ListBoxItem backupListBoxItem = this.ListBackUp.ItemContainerGenerator.ContainerFromItem(msg.Selectedbackup) as ListBoxItem;
                    if (backupListBoxItem != null)
                    {
                        ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(backupListBoxItem);
                        // Finding control from the DataTemplate that is set on that ContentPresenter
                        DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
                        TextBox editBackupDescTb = (TextBox)myDataTemplate.FindName("editBackupDesc", myContentPresenter);
                        editBackupDescTb.Focus();
                        editBackupDescTb.SelectAll();
                    }
                }));

            }
        }

        /// <summary>
        /// 注册快捷键
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            // 获取窗体句柄
            m_Hwnd = new WindowInteropHelper(this).Handle;
            HwndSource hWndSource = HwndSource.FromHwnd(m_Hwnd);
            // 添加处理程序
            if (hWndSource != null) hWndSource.AddHook(WndProc);
        }

        /// <summary>
        /// 所有控件初始化完成后调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            // 注册热键

            /* 获取全部系统配置 */
            var sysCfg = _DataVM.SysConfig;
            if (sysCfg != null)
            {
                List<HotKeyModel> shortCutList = new List<HotKeyModel>();
                if (!string.IsNullOrEmpty(sysCfg.LoadBackupShortcut))
                {
                    string keyStr = sysCfg.LoadBackupShortcut.Replace("Shift", "").Replace("Control", "").Replace("Alt", "").Replace("+", "");
                    EKey selectedKey = (EKey)Enum.Parse(typeof(EKey), keyStr);
                    shortCutList.Add(new HotKeyModel
                    {
                        ActionName = EHotKeyAction.载入备份.ToString(),
                        IsShift = sysCfg.LoadBackupShortcut.Contains("Shift"),
                        IsControl = sysCfg.LoadBackupShortcut.Contains("Control"),
                        IsAlt = sysCfg.LoadBackupShortcut.Contains("Alt"),
                        Key = selectedKey
                    });
                }

                if (!string.IsNullOrEmpty(sysCfg.SelfHelpBackupShortcut))
                {
                    string keyStr = sysCfg.SelfHelpBackupShortcut.Replace("Shift", "").Replace("Control", "").Replace("Alt", "").Replace("+", "");
                    EKey selectedKey = (EKey)Enum.Parse(typeof(EKey), keyStr);
                    shortCutList.Add(new HotKeyModel
                    {
                        ActionName = EHotKeyAction.手动备份.ToString(),
                        IsShift = sysCfg.LoadBackupShortcut.Contains("Shift"),
                        IsControl = sysCfg.LoadBackupShortcut.Contains("Control"),
                        IsAlt = sysCfg.LoadBackupShortcut.Contains("Alt"),
                        Key = selectedKey
                    });
                }

                InitHotKey(shortCutList);
            }
        }

        private bool InitHotKey(List<HotKeyModel> hotKeyModelList = null)
        {
            if (hotKeyModelList != null)
            {
                // 注册全局快捷键
                string failRegisterKeyErrorMsg = HotKeyHelper.RegisterGlobalHotKey(hotKeyModelList, m_Hwnd, out dicKeyRegParam);
                if (!string.IsNullOrEmpty(failRegisterKeyErrorMsg))
                {
                    Messenger.Default.Send<NotifyMessage>(new NotifyMessage
                    {
                        Content = $"注册全局快捷键失败:'{failRegisterKeyErrorMsg}'.",
                        IsAlert = true
                    }); 
                }
            }
            //TODO 

            return true;
        }



        /// <summary>
        /// 窗体回调函数，接收所有窗体消息的事件处理函数
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="msg">消息</param>
        /// <param name="wideParam">附加参数1</param>
        /// <param name="longParam">附加参数2</param>
        /// <param name="handled">是否处理</param>
        /// <returns>返回句柄</returns>
        private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wideParam, IntPtr longParam, ref bool handled)
        {
            if (msg == HotKeyManager.WM_HOTKEY)
            {
                int actionID = wideParam.ToInt32();
                if(actionID == dicKeyRegParam[EHotKeyAction.手动备份])
                {
                    _DataVM.ManualCreateBackup();
                }
                else if (actionID == dicKeyRegParam[EHotKeyAction.载入备份])
                {
                    _DataVM.LoadBackup();
                }
                else
                {
                    //不支持的快捷键
                }
            }

            return IntPtr.Zero;
        }

        private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                {
                    return (childItem)child;
                }
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_DataVM != null)
            {
                _DataVM.SaveData();
            }
        }

        private void editBackupDesc_KeyDown(object sender, KeyEventArgs e)
        {
            //按下enter,确认修改
            if (e.Key == Key.Enter)
            {
                Messenger.Default.Send<ConfirmBackupRenameMessage>(new ConfirmBackupRenameMessage());
            }
        }
    }
}
